# frozen_string_literal: true
require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
require 'mina/rbenv'

set :domain, '120.25.195.239'
set :deploy_to, '/root/estate'
set :repository, 'git@git.oschina.net:insionng/estate.git'
set :branch, 'master'
set :keep_releases, 5
set :rbenv_path, '/root/.rbenv'
set :shared_dirs, ['log', 'tmp/pids', 'tmp/cache', 'vendor/bundle']
set :user, 'root'
set :god_port, '17046'
set :god_config_file, -> { "#{fetch(:current_path)}/config/god.rb" }
set :god_log_file, -> { "#{fetch(:current_path)}/log/god.log" }

task :environment do
  invoke :'rbenv:load'
end

desc 'mina setup'
task setup: :environment do
  in_path fetch(:shared_path) do
    command %(mkdir -p "tmp/pids")
    command %(chmod g+rx,u+rwx "tmp/pids")
    command %(mkdir -p "log")
    command %(chmod g+rx,u+rwx "log")
  end
end

desc 'Restart the application.'
task restart: :environment do
  command "
    # god 正在运行, terminate 后重启
    god -p #{fetch(:god_port)} status  &&
    echo 'God is active, now god.terminate.' &&
    god -p #{fetch(:god_port)} terminate &&
    echo 'God is terminated, now god.init with config file.' &&
    god -p #{fetch(:god_port)} -c #{fetch(:god_config_file)} -l #{fetch(:god_log_file)} ||
    # god 没有运行, 启动
    echo 'God is terminated, now god.init with config file.' &&
    god -p #{fetch(:god_port)} -c #{fetch(:god_config_file)} -l #{fetch(:god_log_file)}
  "
end

task machine_log: :environment do
  in_path fetch(:current_path) do
    command %(tail -f log/machine_uploader.log)
  end
end

desc 'Deploys the current version to the server.'
task deploy: :environment do
  deploy do
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'
    invoke :'deploy:cleanup'

    on :launch do
      invoke :restart
    end
  end
end
